package ldkxingzhe.l365calendar.widget.dialog;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import ldkxingzhe.l365calendar.R;
import ldkxingzhe.l365calendar.fragment.HandleFragmentResult;

/**
 * Created by xingzhe on 16/1/28.
 */
public class DialogFragmentBase extends DialogFragment {
    @SuppressWarnings("unused")
    private static final String TAG = "DialogFragmentBase";

    protected void dismissAndDealWithResult(int resultCode, Intent intent) {
        dismiss();
        HandleFragmentResult handler = getHandlerReference();
        if(handler != null){
            handler.onHandleFragmentResult(getTargetRequestCode(), resultCode, intent);
        }
    }

    private HandleFragmentResult getHandlerReference(){
        if(getTargetFragment() != null){
            if(getTargetFragment() instanceof HandleFragmentResult){
                return (HandleFragmentResult)getTargetFragment();
            }
            Log.e(TAG, "getTartFragment is not null, but is not implements HandleFragmentResult");
        }

        if(getActivity() instanceof HandleFragmentResult){
            return (HandleFragmentResult)getActivity();
        }
        Log.e(TAG, "getTartFragment is null, but getActivity is not implements HandleFragmentsResult");
        return null;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.picker_dialog);
        return getDialog(savedInstanceState);
    }

    @NonNull
    protected Dialog getDialog(Bundle savedInstanceState) {
        Dialog dialog =  super.onCreateDialog(savedInstanceState);
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.requestFeature(Window.FEATURE_NO_TITLE);
        WindowManager.LayoutParams params = window.getAttributes();
        params.gravity = Gravity.BOTTOM;
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        return dialog;
    }

    @Override
    public void setTargetFragment(Fragment fragment, int requestCode) {
        if(!(fragment instanceof HandleFragmentResult)){
            throw new IllegalArgumentException(
                    "DatePicker's target fragment should implement HandleFragmentResult");
        }
        super.setTargetFragment(fragment, requestCode);
    }
}
